<template>
    <view class="pb-180">
        <image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
            mode="aspectFill"></image>
        <u-navbar title="节庆活动审批" :autoBack="true" leftIconColor="#fff" bgColor="transparent" :titleStyle="{ color: '#fff' }"
            safeAreaInsetTop placeholder></u-navbar>
        <view class="w-710 mt-20 bgff pl-32 pr-32 br-20 mgt pb-20">
            <!-- 输入框 -->
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>活动名称</view>
                <input class="trt fs-28" placeholder="请输入" v-model="formData.name" />
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>举办时间</view>
                <view class="trt fs-28 col999 rowsc rowsm" v-if="!formData.startTime" @click="show = true">请选择
                    <u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
                </view>
                <view class="trt fs-28" v-else @click="show = true">{{ formatDate(formData.startTime) }}</view>
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>举办地点</view>
                <input class="trt fs-28" placeholder="请输入" v-model="formData.address" />
            </view>
            <view class="rowsb rowsm h-104" style="border-bottom: 2rpx solid #f1f1f1;">
                <view>主办方</view>
                <input class="trt fs-28" placeholder="请输入" v-model="formData.sponsor" />
            </view>
            <view class="rowsl" style="border-bottom: 2rpx solid #f1f1f1;">
                <view class="mt-20 mb-20">简介</view>
                <textarea class="desc-textarea" v-model="formData.desc" placeholder="请输入..." :maxlength="300"
                    auto-height />
            </view>
        </view>

        <!-- 审批表单控件区域 -->
        <view v-if="formControls.length > 0" class="form-card approval-section">
            <view v-for="control in formControls" :key="control.controlId" class="form-item approval-item">
                <text class="label">{{ control.controlLabel }}</text>
                <view class="w-500">
                    <!-- 文本域控件 -->
                    <view v-if="control.controlType === 'textarea'">
                        <textarea v-model="control.controlValue" :placeholder="`请输入${control.controlLabel}`"
                            class="textarea-input" :disabled="!taskID"></textarea>
                    </view>

                    <!-- 单选框控件 -->
                    <view v-else-if="control.controlType === 'radio'">
                        <radio-group @change="onApprovalChange(control, $event)">
                            <label v-for="(option, optIndex) in control.options" :key="optIndex">
                                <radio :value="String(optIndex)"
                                    :checked="parseInt(control.controlValue) === optIndex" :disabled="!taskID" />
                                <text class="radio-text">{{ option }}</text>
                            </label>
                        </radio-group>
                    </view>

                    <!-- 其他控件类型 -->
                    <view v-else class="approval-other">
                        <input v-model="control.controlValue" :placeholder="`请输入${control.controlLabel}`"
                            class="input-field" :disabled="!taskID" />
                    </view>
                </view>
            </view>
        </view>

        <view class="actions" v-if="!this.taskID">
            <button class="btn primary" @click="onSubmit">提交</button>
            <button class="btn ghost" @click="onDraft">存草稿</button>
            <button class="btn gray" @click="onReset">重置</button>
        </view>
        <view @tap="submit()" class="w-690 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
            style="bottom: 68rpx;left: 30rpx;" v-if="this.taskID">
            确认
        </view>

        <u-datetime-picker :show="show" v-model="formData.startTime" mode="date" @cancel="cancel" @confirm="confirm"></u-datetime-picker>
    </view>
</template>

<script>
import { formDataShow, formDataSave, getEventInfo } from '@/api/sylin/index'

export default {
    data() {
        return {
            show: false,
            formData: {
                name: '',
                startTime: '',
                address: '',
                sponsor: '',
                desc: ''
            },
            taskID: '',
            formControls: [] // 存储解析后的表单控件数据
        }
    },
    computed: {
        navbarHeight() {
            // 如果设置了自定义高度，则使用自定义高度
            if (this.customNavbarHeight) {
                return this.customNavbarHeight;
            }
            // 否则自动计算：状态栏高度 + 导航栏高度
            const systemInfo = uni.getSystemInfoSync();
            // 将px转换为rpx (1px = 2rpx)
            const statusBarHeightRpx = systemInfo.statusBarHeight * 2;
            const navbarHeightRpx = 44 * 2; // 44px = 88rpx
            return statusBarHeightRpx + navbarHeightRpx;
        },
    },
    onLoad() {
        // 接收参数
        this.taskID = this.$route.query.taskID
        this.getTaskData()
        this.getEventInfo()
    },
    methods: {
        getEventInfo() {
            getEventInfo(this.taskID).then(res => {
                this.formData.name = res.data.name
                this.formData.startTime = res.data.startTime
                this.formData.address = res.data.address
                this.formData.sponsor = res.data.sponsor
                this.formData.desc = res.data.content
            })
        },
        // 格式化日期
        formatDate(timestamp) {
            if (!timestamp) return '';
            const date = new Date(timestamp);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        // 提交审批
        submit() {
            // 检查必要参数
            if (!this.taskID) {
                uni.showToast({ title: '任务ID不存在', icon: 'none' })
                return
            }
            
            if (!this.formControls || this.formControls.length === 0) {
                uni.showToast({ title: '没有审批数据', icon: 'none' })
                return
            }
            
            // 参考PC端实现，直接传递对象数组
            const formData = this.formControls.map(control => {
                return {
                    controlId: control.controlId,
                    controlType: control.controlType,
                    controlLable: control.controlLabel, // 注意：PC端用的是controlLable
                    controlIsParam: control.controlValue || '', // 使用controlValue作为controlIsParam
                    controlValue: control.controlValue || '',
                    controlDefault: control.controlDefault || ''
                }
            })
            
            console.log('提交参数:', {
                taskID: this.taskID,
                formData: formData
            })
            
            uni.showLoading({ title: '提交中...' })
            
            formDataSave(this.taskID, formData).then(res => {
                uni.hideLoading()
                console.log('提交响应:', res)
                if (res && res.code === 200) {
                    uni.showToast({ title: '提交成功', icon: 'success' })
                    // 可以添加页面跳转或其他操作
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 1500)
                } else {
                    uni.showToast({ title: res?.msg || '提交失败', icon: 'none' })
                }
            }).catch(err => {
                uni.hideLoading()
                console.error('提交失败:', err)
                uni.showToast({ title: '提交失败', icon: 'none' })
            })
        },
        // 获取审批行数据
        getTaskData() {
            // 只有当taskID存在且有效时才调用API
            if (!this.taskID) {
                console.log('无taskID，跳过获取任务数据')
                return
            }
            formDataShow(this.taskID).then(res => {
                console.log(res, 'res')
                // 处理审批行数据
                if (res && res.code === 200 && res.data && Array.isArray(res.data)) {
                    this.parseFormData(res.data)
                }
            }).catch(err => {
                console.error('获取任务数据失败:', err)
                uni.showToast({ title: '获取任务数据失败', icon: 'none' })
            })
        },
        // 解析审批行数据
        parseFormData(formDataArray) {
            try {
                const formControls = []
                
                formDataArray.forEach(item => {
                    // 解析格式: "FormProperty_xxx--__!!controlType--__!!controlLabel--__!!controlValue--__!!controlDefault"
                    const parts = item.split('--__!!')
                    if (parts.length >= 4) {
                        const controlId = parts[0] // FormProperty_xxx
                        const controlType = parts[1] // textarea, radio, etc.
                        const controlLabel = parts[2] // 批注, 审批意见, etc.
                        let controlValue = parts[3] // f, i, etc.
                        const controlDefault = parts[4] || '' // null, 同意--__--不同意, etc.
                        
                        // 处理 controlValue 中的 null 值
                        if (controlValue === 'null' || controlValue === 'f__!!null') {
                            controlValue = ''
                        }
                        
                        const control = {
                            controlId,
                            controlType,
                            controlLabel,
                            controlValue,
                            controlDefault
                        }
                        
                        // 如果是radio类型，解析选项
                        if (controlType === 'radio' && controlDefault) {
                            control.options = controlDefault.split('--__--').filter(opt => opt.trim())
                        }
                        
                        formControls.push(control)
                    }
                })
                
                console.log('解析后的表单控件:', formControls)
                this.formControls = formControls
                
                // 根据控件类型填充表单
                this.fillFormFromControls(formControls)
                
            } catch (err) {
                console.error('解析审批行数据失败:', err)
            }
        },
        // 根据控件数据填充表单
        fillFormFromControls(controls) {
            controls.forEach(control => {
                switch (control.controlLabel) {
                    case '批注':
                        // 如果有批注字段，可以存储到备注中
                        this.formData.remark = control.controlValue
                        break
                    case '审批意见':
                        // 审批意见通常是radio类型
                        if (control.controlType === 'radio') {
                            this.formData.approvalResult = control.controlValue
                        }
                        break
                    // 可以根据实际需要添加更多字段映射
                }
            })
        },
        // 审批控件值改变事件
        onApprovalChange(control, event) {
            const selectedValue = event.detail.value
            // 确保存储的是字符串类型，与后端数据格式一致
            control.controlValue = String(selectedValue)
            console.log('审批控件值改变:', control.controlLabel, selectedValue)
        },
        // 获取控件值（用于显示当前选中的值）
        getControlValue(control) {
            // 处理空值情况
            if (!control.controlValue || control.controlValue === 'null' || control.controlValue === 'f__!!null') {
                return ''
            }
            
            if (control.controlType === 'radio') {
                // 对于radio类型，返回选中的选项文本
                const selectedIndex = parseInt(control.controlValue)
                if (control.options && control.options[selectedIndex]) {
                    return control.options[selectedIndex]
                }
                return control.controlValue
            }
            return control.controlValue
        },
        // 提交表单
        onSubmit() {
            // 验证表单
            if (!this.formData.name.trim()) {
                uni.showToast({ title: '请输入活动名称', icon: 'none' })
                return
            }
            if (!this.formData.startTime) {
                uni.showToast({ title: '请选择举办时间', icon: 'none' })
                return
            }
            if (!this.formData.address.trim()) {
                uni.showToast({ title: '请输入举办地点', icon: 'none' })
                return
            }
            if (!this.formData.sponsor.trim()) {
                uni.showToast({ title: '请输入主办方', icon: 'none' })
                return
            }
            if (!this.formData.desc.trim()) {
                uni.showToast({ title: '请输入简介', icon: 'none' })
                return
            }

            uni.showLoading({ title: '提交中...' })
            
            // 这里应该调用相应的API接口
            // const data = { ...this.formData, postFlag: 1 }
            // submitActivity(data).then(res => { ... })
            
            // 模拟API调用
            setTimeout(() => {
                uni.hideLoading()
                uni.showToast({ title: '提交成功', icon: 'success' })
                this.onReset()
            }, 1000)
        },
        // 存草稿
        onDraft() {
            // 验证表单
            if (!this.formData.name.trim()) {
                uni.showToast({ title: '请输入活动名称', icon: 'none' })
                return
            }
            if (!this.formData.desc.trim()) {
                uni.showToast({ title: '请输入简介', icon: 'none' })
                return
            }

            uni.showLoading({ title: '保存中...' })
            
            // 这里应该调用相应的API接口
            // const data = { ...this.formData, postFlag: 0 }
            // submitActivity(data).then(res => { ... })
            
            // 模拟API调用
            setTimeout(() => {
                uni.hideLoading()
                uni.showToast({ title: '草稿已保存', icon: 'success' })
                this.onReset()
            }, 1000)
        },
        // 重置表单
        onReset() {
            this.formData = {
                name: '',
                startTime: '',
                address: '',
                sponsor: '',
                desc: ''
            }
        },
        cancel() {
            this.show = false;
        },
        confirm(e) {
            this.formData.startTime = e.value;
            this.show = false;
        }
    },
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
    position: fixed;
    top: 0;
    left: 0;
    width: 750rpx;
    z-index: 1;
}
.desc-textarea {
    width: 100%;
    min-height: 200rpx;
    background: #f7f7f7;
    border-radius: 16rpx;
    padding: 24rpx;
    font-size: 28rpx;
    color: #333;
    border: none;
    resize: none;
}

/* 绿色主题变量 */
$brand: #29a74d;
$brand-weak: #e9f7ee;
$brand-border: #cfe9db;
$brand-strong: #239243;

.form-card {
    width: 710rpx;
    margin: 0 auto;
    background: #fff;
    border: 1rpx solid #eef2f7;
    border-radius: 22rpx;
    padding: 18rpx 18rpx;
    box-shadow: 0 10rpx 24rpx rgba(12, 18, 28, .06);
    margin-top: 24rpx;
}

.form-item {
    display: flex;
    align-items: center;
    padding: 16rpx 8rpx;
}

.form-item+.form-item {
    border-top: 1rpx dashed #eef2f7;
}

.label {
    width: 220rpx;
    color: #374151;
    font-size: 28rpx;
}

/* 审批表单样式 */
.approval-section {
    margin-top: 24rpx;
}
.approval-item {
    border-top: 1rpx dashed #eef2f7;
}

.approval-item:first-child {
    border-top: none;
}

.textarea-input {
    width: 100%;
    min-height: 120rpx;
    padding: 16rpx;
    border: 1rpx solid $brand-border;
    border-radius: 14rpx;
    background: $brand-weak;
    font-size: 28rpx;
    color: #111827;
    resize: none;
}

.textarea-input:disabled {
    background: #f9fafb;
    color: #9ca3af;
}

.radio-item {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;
    padding: 12rpx 16rpx;
    border-radius: 12rpx;
    background: #f9fafb;
    border: 1rpx solid #e5e7eb;
}

.radio-item:last-child {
    margin-bottom: 0;
}

.radio-text {
    margin-left: 12rpx;
    margin-right: 20rpx;
    font-size: 28rpx;
    color: #374151;
}

.radio-item:disabled {
    opacity: 0.6;
}

.approval-other {
    width: 100%;
}

.input-field {
    width: 100%;
    height: 72rpx;
    padding: 0 20rpx;
    border: 1rpx solid $brand-border;
    border-radius: 14rpx;
    background: $brand-weak;
    font-size: 28rpx;
    color: #111827;
}

.input-field:disabled {
    background: #f9fafb;
    color: #9ca3af;
}

.w-500 {
    width: 500rpx;
}

/* 底部按钮 */
.actions {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 18rpx;
    padding: 26rpx 12rpx;
}

.btn {
    height: 68rpx;
    line-height: 68rpx;
    border-radius: 14rpx;
    font-size: 28rpx;
    border: none;
}

.btn.primary {
    background: linear-gradient(90deg, lighten($brand, 2%), $brand-strong);
    color: #fff;
    box-shadow: 0 6rpx 14rpx rgba(37, 154, 68, .22);
}

.btn.ghost {
    background: #fff;
    color: $brand-strong;
    box-shadow: inset 0 0 0 1rpx $brand-border;
}

.btn.gray {
    background: #e5e7eb;
    color: #374151;
}
</style>